package org.ziegler.javabase.thread.shutdown;

import org.ziegler.javabase.thread.DelayUtil;

public class ShutdownTest2 {
    public static void main(String[] args) {
        System.out.println("ShutdownHootTest.testHookSystemExit");

        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            e.printStackTrace();
        });

        final Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });
        thread.start();

        new Thread(() -> {
            DelayUtil.second(2);
            System.out.println("delay 2 second and then exit");
            System.exit(0);
        }).start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // 调用
            System.out.println("run addShutdownHook");
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }
}
